using System;
using System.Collections.Generic;
using System.IO;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Video;

public class VideoPlayerController : MonoBehaviour
{
    public static VideoPlayerController instance;
    public VideoPlayer videoPlayer;
    public List<string> videoUrl;//视频地址
    private int videoIndex = 0;//视频索引
    private int coin;//投币数
    private int coinCount;//投币总数
    private int coinCountForever;//永久投币总数
    public int currency;//游玩币数
    [SerializeField] private TextMeshProUGUI coinCountUI;//投币总数文本
    [SerializeField] private TextMeshProUGUI coinUI;//投币数+游玩币数文本
    [SerializeField] private TextMeshProUGUI pleaseCoinUI;//请投几币文本


    public bool isPlay;//游戏状态
    private float gameTimer = 1;//游戏倒计时
    public float gameDefaultTime = 60;//每次投币增加的时间
    private float idleTimer = 0;//返回待机界面计时器
    private int idleTime = 0;//返回待机界面的时间
    private float audioTimer = 0;//请投币语音时间
    [SerializeField] private GameObject gameTimeUI;//倒计时文本

    [SerializeField] private GameObject idleUI;//待机界面
    bool gameContinue;//持续游戏

    [SerializeField] private GameObject jiantou;//控制左右箭头对象显示


    private void Awake()
    {
        if (instance != null)
        {
            Destroy(this);
        }
        else
        {
            instance = this;
        }
    }

    void Start()
    {

        // 播放视频结束事件
        videoPlayer.loopPointReached += OnVideoEnded;
        // 获取投币总数和游玩投币
        GetCoinData();
        // 设置投币数文本
        SetupCoinText();
        // 设置倒计时文本
        SetCountdowmText();
    }

    private void Update()
    {
        audioTimer -= Time.deltaTime;
        // 跳转设置
        if (ComTrans.Instance.GetsetSerial())
        {
            SceneManager.LoadScene(1);
        }
        // 投币测试
        if (Input.GetKeyDown(KeyCode.Alpha0))
        {
            ComTrans.Instance.coinSerial = true;
        }
        // 获取投币信号
        GetCoinSerial();
        // 游戏状态
        if (isPlay)
        {
            idleTimer = 0;
            gameTimer -= Time.deltaTime;
            if (ComTrans.Instance.gameOpen == 0)
                ComTrans.Instance.ChangeGame();
            // 游戏结束
            GameEnd();
        }
        else
        {
            idleUI.SetActive(true);
        }
        // 设置倒计时文本
        SetCountdowmText();
        // 设置投币数文本
        SetupCoinText();

        if (gameContinue)
        {
            if (coin >= currency)
            {
                coin -= currency;
                gameTimer += gameDefaultTime;
                isPlay = true;
                PlayerPrefs.SetInt("coin", coin);
                PlayerPrefs.Save();
                idleUI.SetActive(false);
                videoPlayer.Play();
                if (ComTrans.Instance.gameOpen == 0)
                    ComTrans.Instance.ChangeGame();
            }
            if (!isPlay)
            {
                idleTimer += Time.deltaTime;
                if (idleTimer >= idleTime)
                {
                    SceneManager.LoadScene(0);
                    if (ComTrans.Instance.gameOpen == 1)
                        ComTrans.Instance.ChangeIdle();
                }
            }
        }
    }


    // 获取投币总数和游玩投币
    private void GetCoinData()
    {
        coin = PlayerPrefs.GetInt("coin", 1);
        coinCount = PlayerPrefs.GetInt("coinCount", 5);
        currency = PlayerPrefs.GetInt("currency", 1);
        gameDefaultTime = PlayerPrefs.GetInt("gameDefaultTime", 60);
        coinCountForever = PlayerPrefs.GetInt("coinCountForever", 0);
        idleTime = PlayerPrefs.GetInt("idleTime", 20);
    }

    // 游戏结束
    private void GameEnd()
    {
        if (gameTimer <= 0)
        {
            gameTimer = 0;
            isPlay = false;
            videoPlayer.Pause();
            ComTrans.Instance.ChangeIdle();
        }
    }

    // 开始游戏
    public void GameStart(int _index = 0)
    {

        if (!isPlay)
        {
            if (coin >= currency)
            {
                coin -= currency;
                gameTimer += gameDefaultTime + 3;
                isPlay = true;
                PlayerPrefs.SetInt("coin", coin);
                PlayerPrefs.Save();
                idleUI.SetActive(false);

                // if (gameContinue)
                // {
                //     videoPlayer.Play();
                //     return;
                // }
                videoIndex = _index;
                ChangeVideo(_index);
                videoPlayer.Play();
                idleUI.transform.GetChild(0).gameObject.SetActive(false);
                idleUI.transform.GetChild(1).gameObject.SetActive(false);
                jiantou.SetActive(false);
                gameContinue = true;
                // if (ComTrans.Instance.gameOpen == 0)
                ComTrans.Instance.ChangeGame();
            }
            else
            {
                if (audioTimer < 0)
                {
                    ComTrans.Instance.audioSource2.PlayOneShot(ComTrans.Instance.audioClip[0]);
                    audioTimer = 5;
                }
            }
        }
    }

    // 视频播放完毕
    private void OnVideoEnded(VideoPlayer _vp)
    {

        Debug.Log("播放完毕1");
        if (gameTimer > 0 && isPlay)
        {
            videoIndex++;
            if (videoIndex >= videoUrl.Count)
            {
                videoIndex = 0;
            }
            ChangeVideo(videoIndex);
            videoPlayer.Play();
        }
    }

    // 切换视频
    public void ChangeVideo(int _index)
    {
        string filePath = "";

        if (_index <= videoUrl.Count)
            filePath = videoUrl[_index];
        else
            filePath = videoUrl[0];

        videoPlayer.url = filePath;
        videoPlayer.Prepare();
        // videoPlayer.Play();
    }

    // 设置投币数文本
    private void SetupCoinText()
    {
        if (PlayerPrefs.GetInt("language", 0) == 0)
        {

            coinCountUI.text = "总投币数:" + coinCount.ToString("D8");//+ ":" + ComTrans.Instance.gameOpen
            coinUI.text = "投币\r\n" + coin.ToString() + "/" + currency;
            pleaseCoinUI.text = "请投" + currency + "币";
        }
        else
        {
            coinCountUI.text = "Total Coins:" + coinCount.ToString("D8");
            coinUI.text = "put in coins\r\n" + coin.ToString() + "/" + currency;
            pleaseCoinUI.text = "Please invest " + currency + " coins";
        }

    }

    // 设置倒计时文本
    private void SetCountdowmText()
    {
        if (isPlay) { gameTimeUI.SetActive(true); }
        else { gameTimeUI.SetActive(false); }
        int minutes = Mathf.FloorToInt(gameTimer / 60);
        int seconds = Mathf.FloorToInt(gameTimer % 60);
        string str = string.Format("{0:D2}: {1:D2}", minutes, seconds);
        gameTimeUI.GetComponent<TextMeshProUGUI>().text = str;
    }

    // 获取投币信号
    private void GetCoinSerial()
    {
        if (ComTrans.Instance.GetCoinSerial())
        {
            coin += 1;
            coinCount += 1;
            coinCountForever += 1;
            PlayerPrefs.SetInt("coin", coin);
            PlayerPrefs.SetInt("coinCount", coinCount);
            PlayerPrefs.SetInt("coinCountForever", coinCountForever);
            PlayerPrefs.Save();
            ComTrans.Instance.audioSource2.PlayOneShot(ComTrans.Instance.audioClip[1]);
        }
    }



    public void Over()
    {
        Application.Quit();
    }

}